package com.shadt.pay.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shadt.core.controller.BaseController;
import com.shadt.core.util.HttpsServiceRequest;
import com.shadt.core.util.IServiceRequest;
import com.shadt.core.util.IpUtil;
import com.shadt.core.util.RandomStringGenerator;
import com.shadt.core.util.Signature;
import com.shadt.pay.model.OrderReceive;
import com.shadt.pay.model.PreReturn;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;


/**
 * 流程测试
 * @author SongR
 *
 */
@Controller
@RequestMapping("/dev")
public class DevController extends BaseController{
	
	/**
	 * 测试shadt统一下单
	 * @param body
	 * @param notifyurl
	 * ba5a610wbbd717828we5841vb2e516c7 wxa007553209f3c8a8 1315614001
	 * 
	 */
	@RequestMapping(value="/unifiedorder")
	public String unifiedorder(HttpServletRequest request){
		System.out.println(IpUtil.getIpAddr(request)+"手机ip");
		String tradeNo = new Date().getTime()+"";
		try {
			OrderReceive or = new OrderReceive();
			or.setAppid("shadt07553209f3c8a8");
			or.setMch_id("16052509440");
			or.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			or.setBody("测试"+tradeNo);
			or.setOut_trade_no(tradeNo);//订单号
			or.setTotal_fee("1");
			or.setNotify_url("http://192.168.0.121:8080/shadt/AppPayController/appnotify.do");
			or.setSign(Signature.getSign(or, "ba5a6102bbd717828ce58412b2e516c8"));
			IServiceRequest is = new HttpsServiceRequest();
			String prePayReturn =is.sendPost("http://116.236.181.2:8688/shadtpay/prepay/unifiedorder", or);
			XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));// 解决XStream对出现双下划线的bug
			xs.alias("xml", PreReturn.class);
			PreReturn preReturn = (PreReturn) xs.fromXML(prePayReturn);
			System.out.println(prePayReturn);
			if(preReturn.getReturn_code().equals("SUCCESS")){
				System.out.println("redirect:http://116.236.181.2:8688/shadtpay/prepay/pay?appid="+preReturn.getApp_id()+"&mch_id="+preReturn.getMch_id() +
						"&out_trade_no=" +tradeNo+
						"&redirect_uri="+tradeNo);
				return "redirect:http://116.236.181.2:8688/shadtpay/prepay/pay?appid="+preReturn.getApp_id()+"&mch_id="+preReturn.getMch_id() +
						"&out_trade_no=" +tradeNo+
						"&redirect_uri="+tradeNo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return "";
	}
}
